<?php

namespace backend\utils;

require_once __DIR__ . '/../../common/extensions/PHPExcel-1.8/Classes/PHPExcel.php';


use Faker\Provider\Uuid;
use PHPExcel_Style_Border;
use Yii;
use yii\base\Exception;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Response;
use ZipArchive;

class AppUtil
{
    const PROJECT_NAME = '专业设置-中职';
    const CODE_SUCCESS = 1;
    const CODE_FAIL = 0;

    // 状态: 1:使用，2:删除
    const STATUS_USE = 1;//使用
    const STATUS_VOID = 2;//删除


    public static function db()
    {
        return Yii::$app->db;
    }

    public static function init_uuid()
    {
        return Uuid::uuid();
    }

    static function get_web_path()
    {
        //返回值 D:\phpstudy_pro\WWW\linghang/backend/web
        return Yii::getAlias('@backend') . DIRECTORY_SEPARATOR . 'web';
    }

    public static function get_file_path_prefix()
    {
        // Yii::$app->request->baseUrl ;// linghang/backend/web
        // Yii::getAlias('@web') ;// linghang/backend/web
        return Yii::getAlias('@web');
    }

    public static function yii_alert($flag, $msg = "添加成功~")
    {
        $flag_t = $flag ? "success" : "error";
        Yii::$app->session->setFlash($flag_t, $msg);
    }

    public static function get_error_msg($model)
    {
        $err_str = '';
        if ($model instanceof Model) {
            foreach ($model->getErrors() as $v) {
                foreach ($v as $str) {
                    $err_str .= $str;
                }
            }
        }

        return $err_str;
    }

    public static function get_error($model, $suffix = '')
    {
        $err_array = [];
        foreach ($model->getErrors() as $key => $v) {
            foreach ($v as $str) {
                $err_array['error_' . $key . $suffix] = $str;
            }
        }
        return $err_array;
    }

    public static function get_web_host()
    {
        return Yii::$app->request->hostInfo;
    }


    public static function download_file($path, $file_name)
    {
        $download_file_flag = true;
        $path = self::get_web_path() . $path;

        try {
            Yii::$app->response->sendFile($path, $file_name)->send();
        } catch (\Exception $e) {
            $download_file_flag = false;
        }

        return $download_file_flag;
    }

    public static function renderAPI($code, $msg = '', $data = [])
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s'),
        ];
    }

    public static function renderClient($code, $msg = '', $opt = "", $data = [])
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'code' => $code,
            'msg' => $msg,
            'opt' => $opt ? $opt : Yii::$app->request->post('opt', ''),
            'data' => $data,
            'time' => date('Y-m-d H:i:s'),
        ];
    }

    public static function renderTeeAPI($data = [])
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'code' => 0,
            'msg' => '',
            'data' => $data,
            'count' => count($data),
        ];
    }

    const FONT_NAME = "宋体";
    const FONT_NAME_BLACK = "黑体";
    const FONT_SIZE = 10;
    const FONT_SIZE_BIG = 14;
    static $excel_all_borders = [
        'borders' => [
            'allborders' => [
                'style' => PHPExcel_Style_Border::BORDER_THIN
            ]
        ]
    ];

    public static function pre_export_excel($fileName, $headArr, $data, $widths = [])
    {
        if (empty($data) || !is_array($data)) {
            $data = [];
        }
        if (empty($fileName)) {
            exit;
        }
        //创建新的PHPExcel对象
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getDefaultStyle()->getFont()->setName(self::FONT_NAME);
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(self::FONT_SIZE);

        $activeSheet = $objPHPExcel->getActiveSheet();
        //设置表头
        $key = ord("A");//65
        $tmpIndex = 0;
        //$headArr表头数据
        foreach ($headArr as $k => $v) {
            $col = \PHPExcel_Cell::stringFromColumnIndex($k);
            $tmpWidth = 20;
            $activeSheet->getColumnDimension($col)->setWidth($tmpWidth);
            $activeSheet->getStyle($col)->getAlignment()->setWrapText(false);//自动换行
            $activeSheet->getStyle($col . 1)->getFont()->setName(self::FONT_NAME_BLACK);
            $activeSheet->getStyle($col . 1)->getFont()->setSize(self::FONT_SIZE);
            $activeSheet->setCellValue($col . '1', $v);
            $tmpIndex++;
            $key += 1;
        }
        $rowIndex = 2;
        // $data --> 表格的具体数据
        $col = 'A';
        foreach ($data as $key => $rows) {
            $span = ord("A");
            foreach ($rows as $keyName => $value) {
                $col = \PHPExcel_Cell::stringFromColumnIndex($keyName);
                $activeSheet->setCellValue($col . $rowIndex, $value);
                $activeSheet->getStyle($col)->getAlignment()->setWrapText(false);
                $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

                if ($keyName == (count($rows) - 1)) {
                    $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                }
                $span++;
            }
            $rowIndex++;
        }

        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $col . ($rowIndex - 1))->applyFromArray(self::$excel_all_borders);

        if ($widths) {
            foreach ($headArr as $k => $v) {
                if (isset($widths[$k])) {
                    $col = \PHPExcel_Cell::stringFromColumnIndex($k);
                    $activeSheet->getColumnDimension($col)->setWidth($widths[$k]);
                    $activeSheet->getStyle($col . '1')->getFont()->setBold(true);//加粗
                    $activeSheet->getStyle($col . '1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                    $activeSheet->getStyle($col . '1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                } else {
                    break;
                }
            }
        }
        self::export_excel($fileName, $objPHPExcel);
    }

    public static function pre_export_excel_sheets($fileName, $data, $widths = [])
    {
        if (empty($data) || !is_array($data)) {
            $data = [];
        }
        if (empty($fileName)) {
            exit;
        }
        //创建新的PHPExcel对象
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getDefaultStyle()->getFont()->setName(self::FONT_NAME);
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(self::FONT_SIZE);


        foreach ($data as $sheet_k => $data_item) {
            if ($sheet_k >= 0) {
                $objPHPExcel->createSheet();  // 创建sheet
            }

            $objPHPExcel->setActiveSheetIndex($sheet_k);
            $objPHPExcel->getActiveSheet()->setTitle($data_item[1]);
            $activeSheet = $objPHPExcel->getActiveSheet();

            $rowIndex = 1;
            // $data_item --> 表格的具体数据
            foreach ($data_item[0] as $key => $rows) {
                $span = ord("A");
                foreach ($rows as $keyName => $value) {
                    $col = \PHPExcel_Cell::stringFromColumnIndex($keyName);
                    $activeSheet->setCellValue($col . $rowIndex, $value);
                    $activeSheet->getStyle($col)->getAlignment()->setWrapText(false);
                    $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                    $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

                    $activeSheet->getStyle($col . $rowIndex)->getFont()->setName(self::FONT_NAME_BLACK);
                    $activeSheet->getStyle($col . $rowIndex)->getFont()->setSize(self::FONT_SIZE);

                    if ($keyName == (count($rows) - 1)) {
                        $activeSheet->getStyle($col . $rowIndex)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                    }
                    $span++;
                }
                $rowIndex++;
            }
        }


        self::export_excel($fileName, $objPHPExcel);
    }

    public static function export_excel($fileName, $objPHPExcel)
    {
        $fileNameExt = $fileName . '.xlsx';
        $encoded_filename = urlencode($fileNameExt);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        //$objPHPExcel->getActiveSheet()->setTitle($fileName);
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/i", $ua) || preg_match("/Trident/i", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else {
            if (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileNameExt . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $fileNameExt . '"');
            }
        }
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    public static function parseProduct($fileName)
    {
        try {
            $filePath = $fileName;
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            $canRead = $PHPReader->canRead($filePath);

            if (!$canRead) {
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if (!$PHPReader->canRead($filePath)) {
                    return false;
                }
            }

            $PHPExcel = $PHPReader->load($filePath);
            //$sheetCount = $PHPExcel->getSheetCount();
            $currentSheet = $PHPExcel->getSheet(0);
            $allColumn = $currentSheet->getHighestColumn();
            $allRow = $currentSheet->getHighestRow();
            $allColumn = \PHPExcel_Cell::columnIndexFromString($allColumn);
            // echo '$allColumn:' . $allColumn . ' $allRow:' . $allRow . PHP_EOL;

            $ret = [];
            //循环读取数据，默认编码是utf8，这里转换成gbk输出
            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
                $ret[$currentRow] = [];
                for ($currentColumn = 0; $currentColumn <= $allColumn; $currentColumn++) {
                    $address = \PHPExcel_Cell::stringFromColumnIndex($currentColumn) . $currentRow;
                    $ret[$currentRow][] = trim($currentSheet->getCell($address)->getFormattedValue());
                }
            }
            return array_values($ret);
        } catch (Exception $ex) {
            return [$ex->getMessage()];
        }

    }

    const TIME_TYPE_CURR = 'curr';

    public static function get_format_time($type = self::TIME_TYPE_CURR)
    {
        switch ($type) {
            case self::TIME_TYPE_CURR:
                $dt = date('Y-m-d H:i:s');
                break;
            default:
                $dt = date('Y-m-d H:i:s');
        }

        return $dt;
    }

    /**
     * 打印数组数据.
     *
     * @param $data
     * @param int $type
     *
     * @time 2019-12-31 AM
     */
    public static function out_array($data, $type = 1)
    {
        if (!is_array($data)) {
            echo 'Data type is not an array.';
            $type = 0;
        }
        switch ($type) {
            case 1:
                print_r($data);
                break;
            case 2:
                echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                break;
            case 3:
                VarDumper::dump($data, 10, true);
                break;
        }
    }

    /**
     * @param $zipname string zip文件名
     * @param $fileArr array 要打包的文件 是一个二维数组的固定格式
     *
     * $fileArr style
     *
     * $fileArr =
     * [
     *   ['file_path' => '/Users/b_tt/Downloads/zip_test/15000.xlsx', 'zip_path' => 'file1/15000.xlsx'],
     *   ['file_path' => '/Users/b_tt/Downloads/zip_test/11926.xlsx', 'zip_path' => 'file1/11926.xlsx'],
     *   ['file_path' => '/Users/b_tt/Downloads/zip_test/15000.xlsx', 'zip_path' => 'file2/15000.xlsx'],
     * ];
     *
     * @time 2020-03-30 PM
     */
    public static function zip_download_file($zipname, $file_array, $chinaName = '')
    {
        if (!is_array($file_array)) {
            echo "param error";
            exit;
        }
        if (!$file_array) {
            echo "下载文件不能为空";
            exit;
        }
        //$zipname = './' . $zipname . '.zip';
        if (!pathinfo($zipname, PATHINFO_EXTENSION)) {
            $zipname = self::get_web_path() . '/files/' . $zipname . '.zip';
        }

        // 要使用该类，需要先启用 extension=php_zip.dll
        if (!extension_loaded("zip")) {
            echo "zip extension loaded fail";
            exit;
        }

        // 如果 zip_path 一样则会覆盖
        $count_values = array_count_values(ArrayHelper::getColumn($file_array, 'zip_path'));
        foreach ($count_values as $zip_path => $co) {
            $dir_name = pathinfo($zip_path, PATHINFO_DIRNAME);
            $ext = pathinfo($zip_path, PATHINFO_EXTENSION);
            $file_name = pathinfo($zip_path, PATHINFO_FILENAME);

            $i = 0;
            foreach ($file_array as $k => $v) {
                if ($v['zip_path'] == $zip_path) {
                    if ($i > 0) {
                        $file_array[$k]['zip_path'] = $dir_name . '/' . $file_name . "({$i})." . $ext;
                    }
                    $i++;
                }
            }
        }

        try {
            $zip = new ZipArchive();
            $res = $zip->open($zipname, ZipArchive::CREATE);
            if ($res === true) {
                foreach ($file_array as $file) {
                    // 这里将服务器上的文件添加到下载内容中，并重新赋值下载zip文件内该文件的路径
                    if (file_exists($file ['file_path'])) {
                        $zip->addFile($file ['file_path'], $file ['zip_path']);
                    }
                }
                $zip->close();
                // 下载
                if (!$chinaName) {
                    Yii::$app->response->sendFile($zipname)->send();
                } else {
                    Yii::$app->response->sendFile($zipname, $chinaName)->send();
                }
            } else {
                echo 'create zip err ';
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());

        }

        //删除
        @unlink($zipname);
    }


    /**
     * 时间转日期
     *
     * @time 2020-04-17 AM
     */
    public static function time_to_date($time)
    {
        if (intval($time) <= strtotime('1970-01-01')) {
            return "";
        }

        return date('Y-m-d', intval($time));
    }

    /**
     * 截取字符串到指定长度
     *
     * @time 2020-04-17 AM
     */
    public static function cut_hanzi_by_len($name, $length = 20)
    {
        return mb_strlen($name) > $length ? mb_substr($name, 0, $length) . '...' : $name;
    }

    const FORWARD = 'forward';  // 向前
    const BACKWARD = 'backward';// 向后

    /**
     * 获取年份
     *
     * @time 2020-05-27 PM
     */
    public static function get_years($count, $dir = self::FORWARD, $start_year = '')
    {
        if (!$start_year) {
            $start_year = date('Y');
        }
        $years = [];

        for ($i = 0; $i < $count; $i++) {
            if ($dir == self::FORWARD) {
                $timestramp = strtotime($start_year) + 86400 * 365 * $i;
            }
            if ($dir == self::BACKWARD) {
                $timestramp = strtotime($start_year) - 86400 * 365 * $i;
            }
            $years[] = date('Y', $timestramp);

        }
        sort($years);

        return $years;
    }

    /**
     * 数字转汉字, 仅仅支持数字小于一百的
     *
     * @time 2020-05-28 AM
     */
    public static function num2Hans($num)
    {
        $num = intval($num);
        $hans = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
        $firstNum = intval(floor($num / 10.0));
        $prefix = "";
        if ($firstNum == 1) {
            $prefix = "十";
        } elseif ($firstNum > 1) {
            $prefix = $hans[$firstNum] . "十";
        }
        $yuNum = $num % 10;
        $suffix = "";
        if ($yuNum > 0) {
            $suffix = $hans[$yuNum];
        }
        if (!$prefix && !$suffix) {
            return "零";
        }

        return $prefix . $suffix;
    }


    const ONLINE_VIEW_FILE_URL = 'https://doctrans.36ve.com?ssl=1&furl=';

    /**
     * 在线预览文件 url生成
     *
     * @time 2020-12-28
     */
    public static function fileView($path)
    {
        return self::ONLINE_VIEW_FILE_URL . Yii::$app->request->hostInfo . '/xcgcs' . $path;
    }

    /**
     * 根据当前所运行的操作系统获取文件名
     */
    public static function getFileName($filename)
    {
        return stripos(self::getSystemName(), 'win') !== false ? iconv('utf-8', 'gbk', $filename) : $filename;
    }

    /**
     * 获取当前所运行的操作系统的名称
     */
    public static function getSystemName()
    {
        return strtolower(php_uname('s'));
    }

    static function sort_multi_field()
    {
        $arr = [
            [9, 8, 7, 6, 5, 3],
            [9, 8, 7, 6, 4, 1],
            [9, 8, 7, 5, 5, 2],
            [9, 8, 6, 6, 5, 3],
            [9, 7, 7, 6, 5, 4],
            [2, 8, 7, 6, 5, 4],
        ];

        $c1 = array_column($arr, 0);
        $c2 = array_column($arr, 1);
        $c3 = array_column($arr, 2);
        $c4 = array_column($arr, 3);
        $c5 = array_column($arr, 4);
        $c6 = array_column($arr, 5);

        array_multisort($c1, SORT_ASC,
            $c2, SORT_ASC,
            $c3, SORT_ASC,
            $c4, SORT_ASC,
            $c5, SORT_ASC,
            $c6, SORT_ASC,
            $arr
        );

        foreach ($arr as $v) {
            echo json_encode($v) . PHP_EOL;
        }
    }

}
